<?php
/*
 * YahooGeo Geocoding for cakePHP
 * For more on the Yahoo! REST API for Geocoding, check out
 * http://developer.yahoo.com/maps/rest/V1/geocode.html
 * Comments, bug reports are welcome digitalspaghetti AT gmail DOT com
 * @author Tane Piper aka digitalspaghetti
 * @website: http://webrocket.wordpress.com
 * @version 0.2.0
 * @license MIT
 */
class YahooGeoComponent extends Object
{
	var $yahoo = 'http://api.local.yahoo.com/MapsService/V1/geocode?appid=';
	
	// Enter your own Yahoo! API ID (http://developer.yahoo.com/faq/index.html#appid)
	var $YahooApiId = 'YahooDemo';
	
	
	// Error codes that Yahoo returns, currently not implemented
	var $errors = array('400', '403', '503');
	
	var $controller	= true;
	
	/**
	 *	function startup()
	 **/
    function startup(&$controller)
    {
    	$this->controller = &$controller;
    }
	
	/**
	 *	function generate()
	 *	This function makes a REST request to Yahoo's API.  The function
	 *	variables are mapped to the same format as the API.
	 *
	 *	@string apiId
	 *	@string	street
	 *	@string	city
	 *	@string	state
	 *	@string	zip
	 *	@string	location
	 *	@string	output
	 *
	 *	The var location will overide all other variables.  The location
	 *	varable can accept the follwing formats:    
	 *	city, state
	 *	city, state, zip
	 *	zip
	 *	street, city, state
	 *	street, city, state, zip
	 *	street, zip
	 *
	 *	Output is either 'xml' or 'php'.  XML is currently
	 *	only supported, PHP support for serialised PHP in a
	 *	future version.
	 **/
	
	function generate($YahooApiId = null, $street=null, $city=null, $state=null, $zip = null, $location = null, $service='google', $output = 'xml') 
	{
		// Check if the user has specified the apiID
		if($YahooApiId == null){
			$YahooApiId = $this->YahooApiId;
		}
		
		// Check to see what variables are populated
		if ($street) { $street = '&street=' . str_replace(' ', '+', $street); }
		if ($city) { $city = '&city=' . str_replace(' ', '+', $city); }
		if ($state) { $state = '&state=' . str_replace(' ', '+', $state); }
		if ($zip) { $zip = '&zip=' . str_replace(' ', '+', $zip); }
		if ($location) { $location = '&location=' . str_replace(' ', '+', $location); }
		
		// Build the REST URL
		$requestUrl = 'http://api.local.yahoo.com/MapsService/V1/geocode?appid=' . $YahooApiId . $street . $city . $state . $zip . $location . '&output=' . $output;
		
		// Get XML response
		if ($result = simplexml_load_file($requestUrl))
		{
			$output = array();
			$output['Latitude'] = $result->Result->Latitude;
			$output['Longitude'] = $result->Result->Longitude;
			$output['Address'] = $result->Result->Address;
			$output['City'] = $result->Result->City;
			$output['State'] = $result->Result->State;
			$output['Zip'] = $result->Result->Zip;
			$output['Country'] = $result->Result->Country;
			return $output;
		} else {
			// Either the URL is malformed or the service is down.
			print_r('Error connecting to services');	
		}

	}	
}
?>